/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.interactio3d.assembly.webapp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author gestalt
 */
public class AssemblyServlet extends HttpServlet
{
private static final int COPY_BUFFER_SIZE = 4 * 1024;
  
    static private void copy(InputStream in, OutputStream out) throws IOException
    {
        byte[] b = new byte[COPY_BUFFER_SIZE];
        int read;
        int total = 0;
        while ((read = in.read(b)) != -1)
        {
            System.out.printf("Read: %d\n", total += read);
            out.write(b, 0, read);
        }
    }

    protected void processMultipartRequest(HttpServletRequest request, HttpServletResponse response)
        throws FileUploadException, IOException
    {
        ServletFileUpload servletFileUpload = new ServletFileUpload();
        FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(bout);

        while (fileItemIterator.hasNext())
        {
            FileItemStream fileItemStream = fileItemIterator.next();
            if (fileItemStream.isFormField())
            {
                continue;
            }

            String name = fileItemStream.getName();
            if(name.trim().isEmpty())
            {
                continue;
            }

            InputStream in = fileItemStream.openStream();

            
            ZipEntry zipEntry = new ZipEntry(name);
            System.out.println("Creating: " + name);
            zipOutputStream.putNextEntry(zipEntry);
            System.out.print("copy");            
            copy(in, zipOutputStream);
            System.out.println(" done");
            zipOutputStream.closeEntry();
            System.out.println("ok");
            in.close();
        }

        zipOutputStream.finish();
        zipOutputStream.close();

        byte[] zippedData = bout.toByteArray();

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition","attachment; filename=output.zip;");
        response.setIntHeader("Content-length", zippedData.length);

        //response.setHeader("Content-Disposition","inline; filename=output.zip;");
        ServletOutputStream out = response.getOutputStream();
        try
        {            
            out.write(zippedData);
            out.flush();
        }
        finally
        {
            out.close();            
        }

        response.sendRedirect("index.jsp");
    }


    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        if (ServletFileUpload.isMultipartContent(request))
        {
            try
            {
                processMultipartRequest(request, response);
            }
            catch (FileUploadException ex)
            {
                System.out.println(ex.getMessage());
                ex.printStackTrace();
                Logger.getLogger(AssemblyServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else
        {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try
            {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet AssemblyServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet AssemblyServlet at " + request.getContextPath () + "</h1>");
                out.println("</body>");
                out.println("</html>");
            }
            finally
            {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }
    // </editor-fold>
}
